package com.example.demo;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.demo.activity.ResultActivity;
import com.example.demo.activity.UserActivity;
import com.example.demo.entity.Song;
import com.example.demo.entity.User;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int CODE_FOR_REQUEST = 1;
    public static final String TAG = "TestActivityForResult:";
    /**
     * Serializable 传递自定义的java对象
     */
    private Button btn_sz;
    /**
     * Parcelable 传递自定义的java对象
     */
    private Button btn_pa;
    /**
     * 测试:startActivityForResult
     */
    private Button btn_tr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btn_sz = (Button) findViewById(R.id.btn_sz);
        btn_sz.setOnClickListener(this);
        btn_pa = (Button) findViewById(R.id.btn_pa);
        btn_pa.setOnClickListener(this);
        btn_tr = (Button) findViewById(R.id.btn_tr);
        btn_tr.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn_sz:
                User user = new User();
                user.setUsername("高昶");
                user.setPassword("520520");
                Intent intent = new Intent(this, UserActivity.class);
                intent.putExtra("user", user);
                intent.putExtra("from", "Serializable"); //UserActivity中用来区分类别
                startActivity(intent);
                break;
            case R.id.btn_pa:
                Song song = new Song();
                song.setAuthor("周杰伦");
                song.setNumber(100000);
                Intent intent2 = new Intent(this, UserActivity.class);
                intent2.putExtra("song", song);
                intent2.putExtra("from", "Parcelable");
                startActivity(intent2);
                break;
            case R.id.btn_tr:
                Intent intent3 = new Intent(MainActivity.this, ResultActivity.class);
                intent3.putExtra("msg", "我是MainActivity,你是谁？");
                startActivityForResult(intent3, CODE_FOR_REQUEST);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 2) {
            String result = data.getStringExtra("result");
            Log.i(TAG, result);
        }
    }

}